import { Injectable ,Inject}    from '@angular/core';
import 'rxjs/add/operator/toPromise';
import { Headers, Http , URLSearchParams ,RequestOptions,ResponseContentType} from '@angular/http';

import { CONFIG_API } from '../config/config';
import { TokenService } from '../token/token.service';

@Injectable()
export class AjaxService{
	public headers = new Headers({
        'Content-Type': 'application/json',
        'Cache-Control': 'no-cache',
    });
	constructor(
        private http: Http,
        @Inject(CONFIG_API) private Url: string,
        private _tokenService    :TokenService,
    ) { }
	getJson(data) {
        let obj = {};
        data.forEach((e) => { obj[e.name] = this.getMethodFn(e); });
        return obj;
    }

    getMethodFn(e){
        let ojb = {
            'get':e => this.doGet(e),
            'post': e => this.doPost(e),
            'filesaver':e => this.doFileSaver(e),
        }
        return ojb[e.methed](e);
    }

    doPost(data){
        let _self = this;

        return function(param){
            var search: URLSearchParams = new URLSearchParams();

            // if(param){for(let k in param){search.set(k,param[k]);}}
            search.set('api_key',_self._tokenService.getTokenFn());

            // let params: URLSearchParams = new URLSearchParams();
            // params.set('token', token);
            
            return _self.http.post(_self.Url + data.url,param,{ search: search,headers: this.headers})
            .toPromise().then( response => response.json() )
            .catch(_self.handleError);
        }
    }

    doGet(data){ 
        let _self = this;
        return function(param){
           var search: URLSearchParams = new URLSearchParams();

           if(param){for(let k in param){search.set(k,param[k]);}}
           search.set('api_key',_self._tokenService.getTokenFn());
           return _self.http.get(_self.Url + data.url,{ search: search,headers: this.headers})
           .toPromise().then( response => response.json())
           .catch(_self.handleError);
        }   
    	
    }
    
    doFileSaver(data){ 
        let _self = this;
        
        return function(param){
            var search = new URLSearchParams();
            if(param){for(let k in param){search.set(k,param[k]);}}

            let options = new RequestOptions({
                responseType: ResponseContentType.Blob,
                search: search,
                headers: this.headers,
            });

            return _self.http.get(_self.Url + data.url,options)
            .toPromise().then(
                (response:any) => response['_body'],
                error => error.json()
            ).catch(_self.handleError);
        }   
    }

	private handleError(error: any){
	    console.error('error : An error occurred');
	    return Promise.reject(error.json());
	}
}
